package com.mxprojects.views
{
	import com.mxprojects.constructors.ButtonConstructor;
	import com.mxprojects.constructors.Divider;
	import com.mxprojects.constructors.ImageDisplay;
	import com.mxprojects.constructors.PopupWindow;
	import com.mxprojects.constructors.SimpleTextField;
	import com.mxprojects.gui.DefaultDialog;
	import com.mxprojects.gui.Icon;
	import com.mxprojects.gui.Styles;
	import com.mxprojects.io.BoardCookie;
	import com.mxprojects.io.Config;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.DeepLinking;
	import com.mxprojects.io.ServerHandler;
	import com.mxprojects.io.TagParser;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TextEvent;
	import flash.text.TextFieldAutoSize;
	
	public class ProfileWindow
	{
		private static const ICON_X:int = 330;
		private static const LAST_TOPIC_MAX_LENGTH:int = 30;
		private static const DEFAULT_AVATAR:String = "avatar-default.jpg";
		private static const TEXT_OFFSET:int = -3;
		
		protected static const ACTION_VIEW_PROFILE:String = "viewUser";
		
		protected static var action:String;
		
		private static var nextX:int = 0;
		private static var nextY:int = 0;
		private static var padNextY:Boolean = false;
		private static var profileWindow:PopupWindow;
		private static var profileHolder:Sprite;
		private static var serverHandler:ServerHandler = new ServerHandler();
		private static var socialIconHeight:int = 0;
		
		
		public static function view(username:String, userID:int):void {
			//will pop open a window to give a little more info about that username
			
			//create the popup
			if(profileWindow != null){
				closeProfile();
			}
			
			profileWindow = new PopupWindow(Config.DEFAULT_POPUP_WIDTH, Config.DEFAULT_POPUP_HEIGHT, Language.main(Word.PROFILE), closeProfile);
			profileWindow.createActionButton(Language.main(Word.CLOSE), closeProfile);
			
			//reset the vars
			nextX = 0;
			nextY = 0;
			socialIconHeight = 0;
			
			//add the username to the title bar as well
			//profileWindow.extraTitle(username);
			
			//get the data
			var dataToSend:Object = new Object();
			dataToSend.userID = userID;
			dataToSend.action = ACTION_VIEW_PROFILE;
			dataToSend.avatarDir = Config.INSTALL_DIRECTORY + Config.IMAGE_DIRECTORY + Config.AVATAR_UPLOAD_SUB_DIRECTORY;
			
			serverHandler.transmitData("profile.php", dataToSend);
			serverHandler.listenForData(showUserProfile);
		}
		
		private static function showUserProfile(event:CustomEvent):void {
			//snag the data
			var profileData:Object = event.getServerData();
			
			if(profileData.output == "mysqlError"){
				DefaultDialog.show(Language.main(Word.ERROR_MYSQL) + "<br>" + profileData.mysqlError, false);
				return;
			}
			
			//make section holders
			profileHolder = new Sprite();
			profileHolder.x = Math.round(profileWindow.titleText.x + Config.TEXT_PADDING/2);
			profileHolder.y = Math.round(profileWindow.titleText.y +  profileWindow.titleText.height + Config.TEXT_PADDING);
			
			//position the information in the profile popup window
			//this will fix any legacy avatars that are trying to pull from a website instead of a local install
			var url:String = profileData.avatarURL;
			//tack on the image directory and set it up
			if(url == "" || url.substr(0, 7) == "http://"){
				//give them the default avatar
				url = DEFAULT_AVATAR;
			}
			url = Config.INSTALL_DIRECTORY + Config.IMAGE_DIRECTORY + Config.AVATAR_UPLOAD_SUB_DIRECTORY + url;
			var avatarImage:ImageDisplay = new ImageDisplay(url, "", Config.MAX_AVATAR_WIDTH, Config.MAX_AVATAR_HEIGHT, false);
			
			//if the image fails, then load the default
			avatarImage.addEventListener(ImageDisplay.ERROR_IMAGE_NOT_FOUND, loadDefaultImage, false, 0, true);
			profileHolder.addChild(avatarImage);
			
			
			//put the various elements on
			nextX = Config.MAX_AVATAR_WIDTH + Config.TEXT_PADDING;
			nextY = TEXT_OFFSET;
			
			var username:SimpleTextField = createTextElement("<span class=\"profileUsername\">" + profileData.username + "</span>");			
			//add the title
//			var title:SimpleTextField = new SimpleTextField("<span class=\"profileSmallElement\">" + profileData.title + "</span>");
//			title.x = username.x + username.width + Config.TEXT_PADDING;
//			title.y = Math.round(username.y + username.height/2 - title.height/2);
//			profileHolder.addChild(title);
			var title:SimpleTextField = createTextElement("<span class=\"profileTitle\">" + profileData.title + "</span>");
			
			//the first bit of stuff needs a little gap
			padNextY = true;
			
			//handle the join date and last online date
			var joined:SimpleTextField = createTextElement("<span class=\"profileSmallElement\">" + profileData.posts + " " + Language.main(Word.POSTS_SINCE) + " " + profileData.joined + "</span>");
			
			//turn off the padding since we don't need it
			padNextY = false;
			
			var lastOnline:SimpleTextField = createTextElement("<span class=\"profileSmallElement\">" + Language.main(Word.LAST_ONLINE) + ": " + profileData.lastOnline + "</span>");
			
			//make sure the thread topic isn't too large
			var lastThreadTopic:String = profileData.lastThreadTopic;
			if(lastThreadTopic.length > LAST_TOPIC_MAX_LENGTH){
				//split the post up into words
				var chunks:Array = lastThreadTopic.split(" ");
				lastThreadTopic = "";
				
				//start patching together the last post
				for(var i:int = 0; i < chunks.length; i++){
					if(chunks[i].length + lastThreadTopic.length <= LAST_TOPIC_MAX_LENGTH){
						lastThreadTopic += chunks[i] + " ";
					}
				}
				
				//take of the last space and add ...
				lastThreadTopic = lastThreadTopic.substring(0, lastThreadTopic.length - 2) + "...";
			}
			
			//stick it all together
			var lastPost:SimpleTextField = createTextElement("<span class=\"profileSmallElement\">" + Language.main(Word.LAST_POST) + ": " + 
													"<a class=\"profileLastThreadLink\" href=\"event:"+Word.POSTS+","+profileData.lastThreadID+"\">" + 
													lastThreadTopic + "</a>" + "</span>");
			lastPost.addEventListener(TextEvent.LINK, viewThread, false, 0, true);
			
			//create a divider 
			var divider:Divider = createDivider();
			
			//handle the signature
			padNextY = true;
			nextX = 0;
			var signature:SimpleTextField = createTextElement("<span class=\"profileSignature\">" + 
													 TagParser.convertToHtml(profileData.signature) + "</span>", 
													 2, 
													 Math.round(profileWindow.width - profileHolder.x*2));			
			
			//set the height of the window based on sig height
			profileWindow.changeHeight(profileHolder.y + nextY + Config.TEXT_PADDING*3);
			
			//reset the padding for the next time somene opens the profile
			padNextY = false;
			
			//start the social stuff/pm/website			
			createIcons(profileData);
			
			//add it to the popup
			profileWindow.addContent(profileHolder);
		}
		
		private static function sendPrivateMessage(username:String):void {
			//close the profile window
			profileWindow.rollUp();
			//closeProfile();
			
			//open the private message panel and pre-populate the username
			PrivateMessages.load(username);
		}
		
		private static function viewThread(event:TextEvent):void {
			//close the profile window and bring them to the thread
		closeProfile();
			
			//split up the array
			var postInfo:Array = event.text.split(",")
			DeepLinking.setLink(postInfo[0], DeepLinking.createLinkArray(postInfo[1]));
		}
		
		private static function createTextElement(content:String, rowCount:int = 1, forceWidth:int = 0):SimpleTextField {
			//this will create various name: value pairs that we want to show
			var textContent:SimpleTextField = new SimpleTextField(content, rowCount, false, forceWidth);
			
			if(rowCount > 1){
				textContent.autoSize = TextFieldAutoSize.CENTER;
				textContent.htmlText = content;
			}
			
			//set the X/Y of the element
			textContent.x = nextX;
			textContent.y = nextY;
			
			if(padNextY){
				textContent.y += Config.TEXT_PADDING/2;
				nextY += Config.TEXT_PADDING/2;
			}
			
			nextY += textContent.height + TEXT_OFFSET;
			
			//add it to the holder
			profileHolder.addChild(textContent);
			
			return textContent;
		}
		
		private static function createDivider():Divider {
			var divider:Divider = new Divider(1, 0, profileWindow.width - profileHolder.x*2);
			Styles.setProperties(divider, ".profileDivider");
			nextY += Config.TEXT_PADDING*2;
			divider.y = nextY;
			nextY += divider.height;
			profileHolder.addChild(divider);
			
			return divider;
		}
		
		private static function createIcons(profileData:Object):void {
			
			var iconBaseLocation:String = Config.INSTALL_DIRECTORY + Config.IMAGE_DIRECTORY + Config.EXTRA_UPLOAD_SUB_DIRECTORY;
			
			//in order to get the nextY we need to go from the bottom of the avatar and stack 3 icons
			nextY = Config.MAX_AVATAR_HEIGHT - Config.NETWORK_ICON_HEIGHT*3 - (Config.TEXT_PADDING/2)*2;
			nextX = ICON_X;
			
			//setup the private message button
			var pmIcon:Icon = new Icon(iconBaseLocation + Icon.PRIVATE_MESSAGE, "", sendPrivateMessage, profileData.username);
			placeIcon(pmIcon, true);
			
			//add some text describe the button
			var privateText:SimpleTextField = new SimpleTextField("<span class=\"profileSmallElement\">" + 
																	Language.main(Word.PRIVATE) + " " + Language.main(Word.MESSAGE) +
																	"</span>");
			privateText.x = Math.round(pmIcon.x + Config.NETWORK_ICON_WIDTH + Config.TEXT_PADDING/2);
			privateText.y = Math.round(pmIcon.y + Config.NETWORK_ICON_HEIGHT/2 - privateText.height/2);
			profileHolder.addChild(privateText);
			
			//if they are not logged in they can't send a message
			if(BoardCookie.getUser() == null){
				pmIcon.alpha = Config.BUTTON_DISABLED_ALPHA;
				pmIcon.mouseChildren = false;
				privateText.htmlText = "<span class=\"profileDisabledText\">" + privateText.text + "</span>";
			}
			
			//setup the website button
			var webURL:String = profileData.website;
			if(webURL != ""){
				if(webURL.substr(0, 4) != "http"){
					webURL = "http://" + webURL;
				}
				
			}
			var webIcon:Icon = new Icon(iconBaseLocation + Icon.WEBSITE, webURL);
			placeIcon(webIcon, true);
			
			var websiteText:SimpleTextField = new SimpleTextField("<span class=\"profileSmallElement\">" + Language.main(Word.WEBSITE) + "</span>");
			websiteText.x = Math.round(webIcon.x + Config.NETWORK_ICON_WIDTH + Config.TEXT_PADDING/2);
			websiteText.y = Math.round(webIcon.y + Config.NETWORK_ICON_HEIGHT/2 - websiteText.height/2);
			profileHolder.addChild(websiteText);
			
			//if they don't have a site, grey out the options
			if(webURL == ""){
				webIcon.alpha = Config.BUTTON_DISABLED_ALPHA;
				webIcon.mouseChildren = false;
				websiteText.htmlText = "<span class=\"profileDisabledText\">" + websiteText.text + "</span>";
			}
			
			//add the custom networks into the mix
			var totalNetworks:int = profileData.totalNetworks;
			for(var i:int = 0; i < totalNetworks; i++){
				var networkIcon:Icon = new Icon(iconBaseLocation +  profileData["networkIcon"+i], profileData["networkURL"+i]);
				placeIcon(networkIcon);	
			}
		}
		
		private static function placeIcon(icon:Icon, moveY:Boolean = false):void {
			//this will take an icon and make sure that it sets the stage for the next one
			icon.x = nextX;
			icon.y = nextY;
			nextX += Config.NETWORK_ICON_WIDTH + Config.TEXT_PADDING/2;
			if(moveY){
				nextY += Config.NETWORK_ICON_HEIGHT + Config.TEXT_PADDING/2;
				
				//reset the X so they stack
				nextX = ICON_X;
			}
			profileHolder.addChild(icon);
		}
		
		private static function loadDefaultImage(event:Event):void {
			//just incase the image doesn't load
			var url:String = Config.INSTALL_DIRECTORY + Config.IMAGE_DIRECTORY + Config.AVATAR_UPLOAD_SUB_DIRECTORY + DEFAULT_AVATAR;
			var avatarImage:ImageDisplay = new ImageDisplay(url, "", Config.MAX_AVATAR_WIDTH, Config.MAX_AVATAR_HEIGHT, false);
			profileHolder.addChild(avatarImage);
		}
		
		private static function closeProfile(event:MouseEvent = null):void {
			if(profileWindow != null){
				profileWindow.removeFromStage();
				profileWindow = null;
			}
		}

	}
}